package main;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

import main.BaseServlet;
import main.PMF;

import DBClasses.EGSImage;

@SuppressWarnings("serial")
public class GetImage extends BaseServlet
{
	@SuppressWarnings("unchecked")
	@Override
	protected void action(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException
	{
		String result = "Не удалось загрузить изображение...";
		String img_id = req.getParameter("img_id");
		if (img_id != null && img_id != "null" && img_id != "")
		{
			try
			{
				Long id = Long.parseLong(req.getParameter("img_id").toString());
				PersistenceManager manager = PMF.get().getPersistenceManager();
				List<EGSImage> imgs = (List<EGSImage>) manager.newQuery(
						"select from " + EGSImage.class.getName()).execute();
				for (EGSImage egsImage : imgs)
				{
					if (egsImage.getId().equals(id))
					{
						resp.addHeader("Content-Type", "image/jpeg");
						ImagesService imagesService = ImagesServiceFactory
								.getImagesService();
						Image oldImage = ImagesServiceFactory
								.makeImage(egsImage.getImg().getBytes());
						try
						{
							Integer mx = Integer.parseInt(req
									.getParameter("max"));
							if (oldImage.getHeight() > mx
									|| oldImage.getWidth() > mx)
							{
								Transform resize = ImagesServiceFactory
										.makeResize(mx, mx);
								oldImage = imagesService.applyTransform(resize,
										oldImage);
							}
						} catch (Exception ex)
						{
						}
						resp.getOutputStream().write(oldImage.getImageData());
						return;
					}
				}
				manager.close();
				resp.getWriter().write(result);
			} catch (Exception ex)
			{
			}
		} else
			resp.getWriter().write(result);
	}
}
